<template>
  <div>
    <div class="gantt-tab">
      <div class="gantt-box">
        <div class="gantt-box-flex" v-show="viewData.includes('a')">
          <div class="gantt-header">
            <div class="gantt-title">
              <span>船舶排布</span>
            </div>
            <div class="gantt-btn">
              <a-button type="text" @click="savePerson(1)"> <template #icon><SaveOutlined /></template>保存</a-button>
              <a-divider type="vertical" />
              <a-button type="text" @click="savePerson(2)"> <template #icon><ShareAltOutlined /></template>共享</a-button>
              <a-divider type="vertical" />
              <a-button type="text" @click="savePerson(3)">  <template #icon><SendOutlined /></template>发布</a-button>
            </div>
          </div>
          <HightChartsShip  ref="gantt"
                            :ganttConfig="shipGanttConfig"
                            @dropChange="dropChange"
                            @updateGantt="updateGantt"
                            :isRedraw="isRedraw"
                            :allExport="allExport"
                            @exportImg="exportImg"
                            :planId="planId"
                            :schemeId="schemeId"
                            :schedleInfo="schedleInfo"
                            @dropChangeVal="dropChangeVal"
          />
        </div>
        <div class="gantt-box-flex" v-show="viewData.includes('b')">
          <div class="gantt-header">
            <div class="gantt-title">
              <span>货源排布</span>
            </div>
          </div>
          <HightChartsGoods  ref="gantt"
                             :ganttConfig="goodsGanttConfig"
                             :isRedraw="isRedraw"
                             :allExport="allExport"
                             @exportImg="exportImg"
                             @dropChangeVal="dropChangeVal"
          />
        </div>
      </div>
      <div class="gantt-line">
        <SchedulingTimeLine  @historyChange="historyChange" :isAdd="shareAdd" :planId="planId"/>
      </div>
    </div>
      <div class="gantt-margin">
        <SchedulingTable v-show="viewData.includes('c')" :isRedraw="isRedraw"/>
      </div>
  </div>
</template>
<script setup>
import {ref, defineProps, watch, onMounted, getCurrentInstance, defineEmits} from "vue";
import {SaveOutlined, SendOutlined, ShareAltOutlined} from '@ant-design/icons-vue';
import SchedulingTable from "@/pages/LngScheduling/components/SchedulingGantt/SchedulingTable.vue";
import SchedulingTimeLine from "@/pages/LngScheduling/components/SchedulingGantt/SchedulingTimeLine.vue";
import HightChartsShip from '../ScedulGantt/HightChartsShip.vue'
import HightChartsGoods from '../ScedulGantt/HightChartsGoods.vue'
const { proxy  } = getCurrentInstance()
const emit = defineEmits(['updatePlanId', 'getImgData'])
import dayjs from 'dayjs'
import {message} from "ant-design-vue";
const props = defineProps({
  activeKey: {
    type: String,
    default: ''
  },
  viewVal: {
    type: Array,
    default: () => []
  },
  allExport: {
    type: Boolean,
    default: false
  },
  ganttData: {
    type: Object,
    default: () => {}
  },
})
const gantt = ref(null)
const viewData = ref(['a', 'b', 'c'])
const isRedraw = ref(0)
watch(() => props.viewVal, (newVal) => {
  console.log('修改了', newVal)
  if (newVal.length === 0) {
    viewData.value = ['a', 'b', 'c']
  } else  {
    let data = [];
    newVal.map(function (value) {
      data = data.concat(value);
    })
    viewData.value = data
  }
  // isRedraw.value++
})
watch(() => props.ganttData, () => {
  getData()
}, {
  deep: true
})
// 贸易类型
const areas = ref([
  {
    label: '长协',
    value: 1
  },
  {
    label: '中期',
    value: 2
  },
  {
    label: '现货',
    value: 3
  }
])
// 贸易主体
const tradeareas = ref([
  {
    label: '国贸',
    value: 1
  },
  {
    label: '新贸',
    value: 2
  },
])
// 航线
const AirOptions = ref([
  {
    label: '巴拿马运河',
    value:1
  },
  {
    label: '好望角海峡',
    value:2
  },
  {
    label: '苏伊士运河',
    value:3
  }
])
const allExport = ref(props.allExport)

const shipGanttConfig = ref({
  // 数据源
  data: [],
  // 左侧表格列配置
  tableConfig: [],
})
const goodsGanttConfig = ref({
  data: [],
  tableConfig: []
})
watch(() => props.allExport, (newVal) => {
  allExport.value = newVal
})
watch(() => isRedraw.value, (newVal) => {
  isRedraw.value = newVal
}, {
  deep: true
})
const planId = ref('')
watch(() => planId.value, (newVal) => {
  planId.value = newVal
})
const schemeId = ref('')
const getLastData = (val) => {
  shipGanttConfig.value.tableConfig = []
  goodsGanttConfig.value.tableConfig = []
  shipGanttConfig.value.data = []
  goodsGanttConfig.value.data = []
  if(val.schemeInfo) {
    planId.value = val.schemeInfo.planId? val.schemeInfo.planId.toString() : ''
    schemeId.value = val.schemeInfo.schemeId? val.schemeInfo.schemeId.toString() : ''
  } else {
    planId.value = val.planId? val.planId.toString() : ''
    schemeId.value = val.schemeId? val.schemeId.toString() : ''
  }
  let shipData = val.shipNames
  let goodsData = val.goodsNames
  console.log('shipData',shipData)
  shipData.map((item, index) => {
    shipGanttConfig.value.tableConfig.push(item.shipName)
    if (item.details.length > 0 && item.details) {
      item.details.map(child => {
        shipGanttConfig.value.data.push(Object.assign({}, child, {
          createBy: localStorage.getItem('userName'),
          id: child.id.toString(),
          shipContractId: child.shipContractId? child.shipContractId.toString() : null,
          y: index,
          color: colorFn(Number(child.executeStatus)),
          tradeTypeLabel: tradeTypeFn(child.tradeType),
          tradeBodyLabel: tradeBodyFn(child.tradeBody),
          shipTradeBodyLabel: tradeBodyFn(child.shipTradeBody),
          sellerTradeBodyLabel: tradeBodyFn(child.sellerTradeBody),
          shipRouteLabel: shipRouteFn(child.shipRoute),
          schemeId: child.schemeId.toString(),
          resourceContract: child.resourceContract? child.resourceContract.toString() : '',
          sellerResourceContract: child.sellerResourceContract? child.sellerResourceContract.toString() : '',
          completed: child.expectedFullLoadVoyageDays / (child.expectedFullLoadVoyageDays + child.expectedEmptyLoadVoyageDays),
          draggable: true,
          start: dayjs(child.expectedLoadingDate).valueOf(),
          end: dayjs(child.expectedEmptyReturnWindow).valueOf(),
        }))
      })
    }
  })
  goodsData.map((item, index) => {
    goodsGanttConfig.value.tableConfig.push(item.goodsName)
    if (item.details.length > 0 && item.details) {
      item.details.map((child) => {
        goodsGanttConfig.value.data.push(Object.assign({}, child, {
          id: child.id.toString(),
          y: index,
          tradeTypeLabel: tradeTypeFn(child.tradeType),
          tradeBodyLabel: tradeBodyFn(child.tradeBody),
          shipRouteLabel: shipRouteFn(child.shipRoute),
          sellerTradeBodyLabel: tradeBodyFn(child.sellerTradeBody),
          shipTradeBodyLabel: tradeBodyFn(child.shipTradeBody),
          color: colorFn(Number(child.executeStatus)),
          schemeId: child.schemeId.toString(),
          resourceContract: child.resourceContract? child.resourceContract.toString() : '',
          sellerResourceContract: child.sellerResourceContract? child.sellerResourceContract.toString() : '',
          completed: child.expectedFullLoadVoyageDays / (child.expectedFullLoadVoyageDays + child.expectedEmptyLoadVoyageDays),
          draggable: true,
          start: dayjs(child.expectedLoadingDate).valueOf(),
          end: dayjs(child.expectedEmptyReturnWindow).valueOf(),
        }))
      })
    }
  })
  console.log('甘特图', shipGanttConfig.value)
  isRedraw.value++
}
/**
 * 颜色切换
 * */
const colorFn = (i) => {
  // 未下发 #165DFF  已下发(船货排布) 38E9FDA3  执行中（已排布）#FF7D00 已完成 #00B42A 已终止 #9EA0A8A3
  const colors = ['rgba(149,26,230,0.64)',  'rgba(56,233,253,0.64)', 'rgba(0,40,243,0.64)', 'rgba(233,0,26,0.64)', 'rgba(158,160,168,0.64)']
  return colors[i]
}
/**
 * 贸易主体赋值
 * */
const tradeBodyFn = (val) => {
  let lastVal = ''
  tradeareas.value.map(item => {
    if (item.value === val) {
      lastVal = item.label
    }
  })
  return lastVal
}
/**
 * 贸易类型赋值
 * */
const tradeTypeFn = (val) => {
  let lastVal = ''
  areas.value.map(item => {
    if (item.value === val) {
      lastVal = item.label
    }
  })
  return lastVal
}
/**
 * 航线赋值
 * */
const shipRouteFn = (val) => {
  let lastVal = []
  console.log('航线的值', val)
  if (val) {
    if (Array.isArray(val)) {
      return  val.join(',')
    } else {
      let newVal = val.split(',')
      if (newVal.length > 0 && Array.isArray(newVal)) {
        newVal.map(item => {
          AirOptions.value.map(rVal => {
            if (Number(item) === rVal.value) {
              lastVal.push(rVal.label)
            }
          })
        })
      }
      return lastVal.join(',')
    }
  }  else {
    return  lastVal
  }
}
/**
 * 船舶排布甘特图修改
 * */
const changeDropData = ref(
    {
      details: []
    }
)
const dropChange = (val) => {
  changeDropData.value = val
  console.log('挪动', changeDropData.value)
}
const dropChangeVal = (val) => {
  if (val) {
    getData()
  }
}
/**
 * 点击历史调度后
 * */
const historyChange = (val) => {
  console.log('点击历史调度了', val)
  isRedraw.value++
  changeDropData.value = val
 // val.shipNames = val.shipNames.reverse()
  getLastData(val)
}
/**
 * 保存、共享、下发
 * */
const shareAdd = ref(false)
const savePerson = (num) => {
  // let newData = []
  // shipGanttConfig.value.data.map(item => {
  //   if (item.start && item.end || item.executeStatus === 0) {
  //     newData.push(item)
  //   }
  // })
  let changeNew = []
  changeDropData.value.details.map(item => {
    if (item.executeStatus === 0) {
      changeNew.push(item)
    }
  })
  let obj = {
    createBy: localStorage.getItem('userName'),
    saveType: num,
    schemeId: schemeId.value,
    planId: planId.value,
    schemeSaveData: changeDropData.value.details.length > 0 ?  changeNew : shipGanttConfig.value.data,
  }
  proxy.$api.postScheduilingGanttSave(obj).then(res => {
    console.log('点击保存后', res)
    if (num === 2) {
      message.success('共享成功')
      shareAdd.value = true
    }
    if (num === 3) {
      message.success('下发成功')
    }
    if (num === 1) {
      message.success('保存成功')
    }
    getData()
  }).catch(err => {
    message.error(err.resultMsg)
    console.log('错误', err)
  })
}
/**
 * 下发
 * */
const pushSchuild = () => {
  proxy.$api.getScheduilingPushlish(schemeId.value).then(res => {
    console.log('点击下发后', res)
    message.success('下发成功')
  })
}
const getData = () => {
  isRedraw.value++
  proxy.$api.postScheduilingShip({planId: '', schemeId: ''}).then(res => {
    console.log('甘特图信息', res.resultObject)
    let data = res.resultObject
    if (data) {
      getLastData(res.resultObject)
      emit('updatePlanId', planId.value)
    }
    postSecult()
  })
}
/**
 * 更新甘特图
 * */
const updateGantt = (val) => {
  console.log('更新的数据', val)
  let upData = {
    isShare: '',
    schemeId: schemeId.value,
    planId: planId.value,
    shipNames: [],
    goodsNames: [],
    sellerNames: []
  }
  let noArr = []
  let lastYArr = []
  let shipNamesArr = []
  if (val.details) {
    let detailsArr = val.details
    let detailsYArr =  val.tableConfig
    let shipObj = {}
    let goodsObj = {}
    let sellerObj = {}
    if (detailsArr.length > 0) {
      detailsArr.forEach((item) => {
        let {shipName, goodsNum, seller} = item
        if (!shipObj[shipName]) {
          shipObj[shipName] = {
            shipName,
            details: []
          }
        }
        if (!goodsObj[goodsNum]) {
          goodsObj[goodsNum] = {
            goodsName: goodsNum,
            details: []
          }
        }
        if (!sellerObj[seller]) {
          sellerObj[seller] = {
            sellerName: seller,
            details: []
          }
        }
        shipNamesArr.push(item.shipName)
        shipObj[shipName].details.push(item)
        goodsObj[goodsNum].details.push(item)
        sellerObj[seller].details.push(item)
      })
    }
    let newShips = [...new Set(shipNamesArr)]
    console.log('newShips', newShips)
    let shipA = new Set(newShips)
    let shipB = new Set(detailsYArr)
    lastYArr = Array.from(new Set([...shipB].filter(x => !shipA.has(x))))
    if (lastYArr.length > 0) {
      console.log('lastYArr', lastYArr)
      lastYArr.map(AItem => {
        let noObj = {}
        Object.assign(noObj, {
          shipName: AItem,
          details: []
        })
        noArr.push(noObj)
      })
    }
    upData.shipNames = Object.values(shipObj).concat(noArr)
    upData.goodsNames = Object.values(goodsObj)
    upData.sellerNames = Object.values(sellerObj)
    console.log('最后成功的数据', upData)
    isRedraw.value++
    getLastData(upData)
  } else {
    getData()
  }
}
/**
 * 获取船舶排期表
 * */
const schedleInfo = ref([])
const postSecult = () => {
  let obj = {
    planId: planId.value?planId.value: '',
    createBy: localStorage.getItem('userName')
  }
  proxy.$api.postShipSchedule(obj).then(res => {
    console.log('获取船期表', res)
    schedleInfo.value = res.resultObject
  })
}
/**
 * 导出图片
 * */
const exportImg = (val) =>{
  emit('getImgData', val)
}
onMounted(() => {
  getData()
})
</script>

<style lang="scss" scoped>
.gutter-box {
  border: 1px solid #DCDEE0;
  height: 32px;
  line-height: 32px;
  margin-bottom: 24px;
  width: 100%;
}
.gantt-margin {
  margin-top: 10px;
}
.gantt-tab {
  display: flex;
  width: 100%;
  justify-content: space-between;
  .gantt-box {
    width:calc(100% - 330px);
    margin-right: 24px;
    //flex: 1;
  }
  .gantt-line{
    //flex-shrink: 0;
    width: 330px;
    background: #fff;
    margin-bottom: 24px;
  }
}

</style>
